<template>
  <div class="merak-container-has-aside" curPageName="7dsfds53123">
    <div class="merak-aside">
      <el-select
        style="margin-bottom: 30px"
        class="qf_select"
        @change="change_prop_type(curMergeType)"
        v-model="curMergeType"
        :placeholder="$t('merak.placeholder_select')"
      >
        <el-option v-for="item in ownAllType" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-input
        style="margin-bottom: 15px"
        v-model="treeFilter"
        :placeholder="$t('merak.placeholder_filter')"
        @input="value => treeRef?.filter(value)"
      />
      <div class="tree-wrapper">
        <el-scrollbar>
          <!-- noCurCss -->
          <el-tree
            :class="curlevel > 2 ? 'merakTree' : 'merakTree '"
            ref="treeRef"
            node-key="id"
            :data="treedata"
            :default-expanded-keys="expandedKeys"
            :props="{ children: 'childs' }"
            :default-checked-keys="curcheck_id"
            :highlight-current="true"
            :filter-node-method="(value, tree) => tree.label.includes(value)"
            @current-change="changeTreeFilter"
          />
        </el-scrollbar>
      </div>
    </div>

    <div class="merak-card merak-container-has-search" v-waterMarker>
      <div>
        <searchBar
          :close-plan="true"
          ref="searchbarRef"
          :placeholder="$t('goods_attribute.merge_prop_placeholder')"
          :close-advanced="true"
          :search_val="search_val"
          @search-event="searchBarPost"
          :v-model="searchform"
        >
          <template #footer>
            <el-button v-auth="{ authArr: authArr, key: 'mergeadd' }" type="primary" @click="addmerge_btn_open()">
              {{ $t("goods_allocation_merge.add_merge") }}
            </el-button>
          </template>
        </searchBar>
      </div>
      <div class="merak-table-wrapper">
        <MerakXTable
          ref="tableRef"
          v-bind="tableState"
          :columns-by-store="JSON.parse(JSON.stringify(state.columns))"
          :query-columns="handleQueryColumns"
          :query-data="handleQueryData"
          :params="state.params"
          :column-min-width="120"
          :column-type="columnTypeArr"
          :data="state.data"
          :batch-click="handleBatchClick"
        
          :await-params="true"
          :handler-click="handleHandlerClick"
          :enabled-editor="tableEditorAuth"
          @editor-click="handleEditorClick"
        >
          <template #custom_handle="{ row }">

            <el-button
             v-auth="{ authArr: authArr, key: 'mergeCard' }"
              type="primary"
              link
              @click="
                router.push({
                  name: 'mergePropertyCard',
                  query: { propId: row?.merge_prop_id, name: language === 'zh' ? row?.merge_prop_cn : row?.merge_prop_ru }
                })
              "
            >
              {{ $t("merak.detail") }}
            </el-button>




            <el-button
             v-auth="{ authArr: authArr, key: 'mergeexport' }"
              type="primary"
              link
              :disabled="row.has_enum==0"
              @click="enumFun(row?.merge_prop_id,row)"
            >
              {{$t("goods_attribute.mjkey")}}
            </el-button>

             <el-button
             v-auth="{ authArr: authArr, key: 'mergedel' }"
              :type="row.allow_delete==1?'default':'danger'"
              link
              :disabled="row.allow_delete==1"
              @click="delFun(row?.merge_prop_id)"
            >
              {{ $t("merak.delete") }}
            </el-button>



          







          </template>

          <template #sp_type_slots="{ row }">
            <span :style="`color:${row.color}`"> <i class="dian" :style="`background:${row.color}`"></i>{{ row.sp_type }} </span>
          </template>
        </MerakXTable>
      </div>
    </div>
    <!-- 查看详情start -->

    <Transition name="fade" mode="out-in">
      <AddMerge v-if="addmerge_btn" :typeId="cur_type" @close="(refresh, typeId) => handleClose(refresh, typeId)" />
    </Transition>

    <div>
      <el-drawer append-to-body v-model="showRemainingModal">
        <template #header>「{{ xqtitle }}」{{ $t("goods_attribute.mjkey") }}</template>
        <div class="export">
          <el-button v-auth="{ authArr: authArr, key: 'mergeexport' }" size="small" link @click="handleExport">{{
            $t("merak.export_data")
          }}</el-button>
        </div>
        <el-table class="merak-table-container" v-loading="xqloading" max-height="calc(100vh - 140px)" :data="xqfrom">
          <el-table-column prop="merge_propvalue_id" label="属性ID" />
          <el-table-column prop="merge_propvalue_cn" :label="$t('goods_allocation_merge.merge_prop_cn')" />
          <el-table-column prop="merge_propvalue_ru" :label="$t('goods_allocation_merge.merge_prop_ru')" />
          <template #empty>
            <div v-if="xqfrom" style="padding: 100px 40px 0">
              <img :src="EmptyPng" style="object-fit: cover; height: 130px" />
            </div>
          </template>
        </el-table>
      </el-drawer>

      <el-dialog v-model="edit_model" :width="500" align-center append-to-body>
        <template #header>
          <div class="editor-title">{{ $t("merak.edit") }}「{{ $t(`goods_allocation_merge.${edit_modal_arr.curField}`) }}」</div>
        </template>
        <el-form ref="formRef" label-position="top" :model="edit_modal_arr">
          <el-input v-model="edit_modal_arr.curval" class="qf_input" />
        </el-form>
        <template #footer>
          <el-button @click="edit_model = false">{{ $t("merak.cancel") }}</el-button>
          <el-button :disabled="edit_disabled" :loading="edit_loading" type="primary" @click="tdSave(edit_modal_arr)">{{
            $t("merak.confirm")
          }}</el-button>
        </template>
      </el-dialog>
    </div>
    <!-- 查看详情end -->
  </div>
</template>

<script lang="ts" setup name="mergeStats">
import useDateFormat from "@/hooks/useDateFormat";
import AddMerge from "./AddMerge.vue";

import { Plus, Edit, Delete, EditPen, Search } from "@element-plus/icons-vue";
import { useDefaultStore } from "@/stores/modules/default";
import { ref, reactive, onMounted, getCurrentInstance, computed } from "vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import EmptyPng from "@/assets/images/empty.png";
import searchBar from "@/components/SearchBar";
import merakColapse from "@/components/merakColapse/index.vue";
import selectedParams from "@/components/SearchBar/components/selectedParams.vue";
import { exportTableApi } from "@/api/modules/table";
import { useRoute, useRouter } from "vue-router";

import MerakXTable, {
  MerakXTableInstance,
  MerakXTableColumn,
  MerakXTableProps,
  MerakXTableQuery
} from "@/components/MerakXTable";

import {
  getLeftApi,
  getmergeDataApi,
  getmergfieldApi,
  updatamergfieldApi,
  gatEnmuApi,
  mergePropdelete
} from "@/api/modules/goodsArchive/allocation";

import {
  moreConfirm,
  confirmWarningMsg,
  successMsg,
  warnMsg,
  failMsg,
  confirmSuccessMsg,
  delConfimMsg
} from "@/utils/messageUtils";
import { useGlobalStore } from "@/stores/modules/global";

import treeNode from "@/views/personalManagement/a-components/oragnizationTree/index.vue";
import { getLocationParams } from "@/utils/index";

import type { ElForm } from "element-plus";
import I18n from "@/languages/index";
import { watch } from "vue";

const $t = I18n.global.t;

const lang = ref("");
lang.value = $t("lang");
const columnTypeArr = ref([{ type: 'handle', width: lang=='ru'?300:200, slot: 'custom_handle' }]);
const route = useRoute();
const router = useRouter();

const defaultStore = useDefaultStore();
const edit_disabled = ref(false);
const edit_loading = ref(false);

// consumer = "consumer", //消费品
// industrial = "industrial", //工业品
// food = "food" //食品

const { format } = useDateFormat();
type FormInstance = InstanceType<typeof ElForm>;
const leavesRef = ref<FormInstance>();

const { proxy } = getCurrentInstance();

const curMergeType = ref("sale");
const ownAllType = [
  { value: "sale", label: "日用品" },
  { value: "mro", label: "工业品" },
  { value: "food", label: "食品" }
];
const addmerge_btn = ref(false);
const cur_type = ref("");

//   打开添加窗口
const addmerge_btn_open = async e => {
  console.log(cur_type.value);

  addmerge_btn.value = true;
};

const tableRef = ref<MerakXTableInstance>();

//批量操作
const handleBatchClick = async e => {};

// 关闭添加页面
const handleClose = (refresh: boolean, typeId) => {
  console.log(typeId);

  if (refresh) {
    if (cur_type.value == typeId) {
      console.log("相等只刷新右侧");
    } else {
      console.log("不相等刷新所有");
      getLeftFun("sale");
      curMergeType.value = "sale";
    }
    // 因为左侧树已经被选择了  因此任何情况下都刷新列表
    tableRef.value?.reloadData();
  }
  addmerge_btn.value = false;
};

//#region 搜索表单
const search_val = ref("");
const searchFn = e => {
  console.log(e);
  // e.searchVal
  state.params.key_words = e.search;
};

const expandedKeys = ref([]);
const searchbarRef = ref();

// 树点击
const changeTreeFilter: InstanceType<typeof ElTree>["onCurrent-change"] = (data, treeNode) => {
  if (!treeNode.isLeaf) return;
  //   const url = new URL(location.href);
  //   if (data.id === "all") {
  //     url.searchParams.delete("key");
  //   } else {
  //     url.searchParams.set("key", data.id.toString());
  //   }
  // //   treeState.value = data.value.toString();
  //   // 记录浏览器参数
  //   history.pushState({}, "", url);

  curcheck_id.value = [data.id];
  treeRef.value?.setCheckedKeys([data.id]);

  console.log(cur_type.value);

  if (data.id.indexOf("-") > -1) {
    var newarr = data.id.split("-");
    cur_type.value = newarr[1];
  } else {
    cur_type.value = data.id;
  }
  console.log(cur_type.value);

  state.params.type_id = cur_type.value;
  searchbarRef.value.clear();
  state.params.keyword = "";
};

const curlevel = ref(1);

//权限数据
let authArr = ref({});

//列表内容展示区
const handleQueryData: MerakXTableInstance["queryData"] = async ({ page, sorts, filters, from }) => {
  const params: Record<string, any> = {};
  if (!!page) {
    // if (curcheck_id.value[0].indexOf('-') > -1) {
    // 	var newarr = curcheck_id.value[0].split('-');
    // 	cur_type.value = newarr[1]

    // } else {
    // 	cur_type.value = curcheck_id.value[0];
    // }

    Object.assign(params, { ...page, type_id: cur_type.value, keyword: params.search });
  }
  // console.log(from)
  for (let key of Object.keys(from)) {
    if (!!from[key]) {
      params[key] = from[key];
    }
  }
  return await getmergeDataApi(params).then(res => {
    // console.log(res)
    if (res.code == ResultEnum.SUCCESS) {
      let data = res.data;
      Object.assign(authArr, data.auth_list);

      // 权限02
      authArr.value = res.auth_list;
      if (authArr.value?.mergedel.show == false && authArr.value?.mergeCard.show == false && authArr.value?.mergeexport.show == false  ) {
        
        columnTypeArr.value=[];
        
      }

      const { table_data, language } = data as { table_data: Record<string, any>; language: Record<string, any> };
      return table_data;
    }
  });
};

const showRemainingModal = ref(false);
const showRemainingData = ref([]);
const xqfrom = ref();
const xqloading = ref(false);
const xqtitle = ref();
const { language } = useGlobalStore();
const xq_merge_prop_id = ref("");
const xq_table_id = ref("");

//打开查看请假详情
const showRemaining = (merge_prop_id, title) => {
  xqtitle.value = title;
  console.log(merge_prop_id);
  xq_merge_prop_id.value = merge_prop_id;
  xqloading.value = true;
  showRemainingModal.value = true;

  gatEnmuApi({ merge_prop_id: merge_prop_id }).then(res => {
    xqloading.value = false;
    if (res.code == ResultEnum.SUCCESS) {
      xqfrom.value = res.data.table_data.list;
      xq_table_id.value = res.data.table_id;
      // showRemainingData.value = list;
    }
  });
};
const handleExport = () => {
  if (typeof xq_merge_prop_id.value === "undefined" || typeof xq_merge_prop_id.value === "undefined") return;
  // 关闭下载列表
  defaultStore.downVisable = false;

  exportTableApi({
    table_id: xq_table_id.value,
    route_name: `${xqtitle.value}枚举值`,
    route_condition: { merge_prop_id: xq_merge_prop_id }
  }).then(({ code, message }) => {
    if (code == ResultEnum.SUCCESS) {
      showRemainingModal.value = false;
      defaultStore.downVisable = true;
    } else {
      failMsg(res.message);
    }
  });
};

// 单元格编辑保存
const tdSave = row => {
  edit_disabled.value = true;
  edit_loading.value = true;
  updatamergfieldApi({ merge_prop_id: row.rowKey, field: row.curField, value: row.curval }).then(res => {
    edit_disabled.value = false;
    edit_loading.value = false;
    if (res.code == ResultEnum.SUCCESS) {
      edit_model.value = false;
      tableRef.value?.reloadData();
    } else {
      failMsg(res.message);
    }
  });
};

// 表格相关属性
const tableState = reactive<MerakXTableProps>({
  columnsByStore: [],
  rowKey: "merge_prop_id",
  columnType: [{ type: "handle", width: 130, showHandleDropDown: true, slot: "custom_handle" }],
  handles: [
    { type: "enum", text: "枚举值" },
    { type: "delete", text: $t("merak.delete"), color: "red" }
  ]
});

// 操作列下拉选项点击事件
const handleHandlerClick: MerakXTableProps["handlerClick"] = async ({ type, params }) => {
  const propId = params.row?.[tableState.rowKey!];
  // const typeId = params.row?.type_id_val;
  // if (typeof propId === "undefined" || typeof typeId === "undefined") return;
  console.log(params);
  switch (type) {
    case "enum":
     
      break;
    case "delete":
     
      break;
    default:
      break;
  }
};


//删除

const delFun = (propId) => {

      confirmWarningMsg({
        msg: $t("goods_attribute.delete_property_message") ?? "",
        callback: (status: string) => {
          if (status === "confirm") {
            console.log("quedingshanchu");
            mergePropdelete({ merge_prop_id: propId }).then(({ code, message }) => {
              if (code == ResultEnum.SUCCESS) {
                tableRef.value?.reloadData();
                successMsg($t("goods_attribute.delete_property_success"));
              } else {
                failMsg(message);
              }
            });
          }
        }
      });
}


//枚举值
const enumFun = (propId,row) => {
  var title = language === "zh" ? row?.merge_prop_cn : row?.merge_prop_ru;
      showRemaining(propId, title);
}


//表头信息
const handleQueryColumns: MerakXTableInstance["queryColumns"] = async () => {
  return await getmergfieldApi().then(res => {
    if (res.code == ResultEnum.SUCCESS) {
      let data = res.data as MerakXTableQuery.Columns;
      // 克隆表头数据作为列设置的对照数据
      tableState.columnsByStore = JSON.parse(JSON.stringify(data.columns));

      // return {
      // 	...data,
      // 	columns: [...data.columns].map(column => {
      // 	switch (column.field) {
      // 		case "merge_prop_id":
      // 		return { ...column, params: { editor: false } };

      // 		case "merge_prop_cn":
      // 		case "merge_prop_ru":

      // 		case "product_type":
      // 		return { ...column, params: { editor: false } };

      // 		case "qifa_prop_id":
      // 		return { ...column, params: { editor: false } };

      // 		case "qifa_prop":
      // 		return { ...column, params: { editor: false } };

      // 		case "qifa_prop_id":
      // 		return { ...column, params: { editor: false } };
      // 		case "cc_prop_id":
      // 		return { ...column, params: { editor: false } };

      // 		default:
      // 		return { ...column };
      // 	}
      // 	})
      // };

      data.columns.map(column_ever => {
        console.log(column_ever);
        if (column_ever.field == "merge_prop_cn" || column_ever.field == "merge_prop_ru") {
          column_ever["params"] = { editor: true };
        } else {
          column_ever["params"] = { editor: false };
        }
      });

      console.log(data.columns);
      state.columns = data.columns;
      return data;
    }
  });
};

interface Tree {
  label: string;
  children?: Tree[];
}

const handleNodeClick = (data: Tree) => {
  console.log(data);
};
const defaultKey = ref(1);
const treedata: Tree[] = ref([]);

const defaultProps = {
  children: "children",
  label: "label"
};
const treeFilter = ref("");
const treeRef = ref();

const state = reactive<{
  params: Record<string, any>;
  columns: MerakXTableColumn[];
}>({
  params: {
    key_words: ""
  },
  columns: []
});

//触发了快速搜索或者搜索方案
const searchBarPost = params => {
  // console.log(params)

  let postParams = { ...params.params, keyword: params.search };
  state.params = postParams;
};

// 编辑表格
// 给予表格编辑权限

//   获取左侧数据
const curcheck_id = ref([]);
const getLeftFun = type => {
  getLeftApi({ type: type }).then(res => {
    if (res.code == ResultEnum.SUCCESS) {
      for (let index = 0; index < res.data.length; index++) {
        const element = res.data[index];
        element["id"] = element.value + "";
        if (element.childs) {
          for (let index = 0; index < element.childs.length; index++) {
            const son_element = element.childs[index];
            son_element["id"] = element.value + "-" + son_element.value;
          }
        }
      }
      treedata.value = res.data;
      if (!route.query.key) {
        if (treedata.value.length > 0) {
          if (treedata.value[0].childs) {
            curcheck_id.value = [treedata.value[0].childs[0].id];
            treeRef.value?.setCheckedKeys([treedata.value[0].childs[0].id]);
          } else {
            curcheck_id.value = [treedata.value[0].id];
            treeRef.value?.setCheckedKeys([treedata.value[0].id]);
          }

          expandedKeys.value = [treedata.value[0].id];
        } else {
          treedata.value = [{ id: "" }];
        }
      }

      console.log(curcheck_id.value);
	  if(curcheck_id.value.length>0){
		  if (curcheck_id.value[0].indexOf("-") > -1) {
		    var newarr = curcheck_id.value[0].split("-");
		    cur_type.value = newarr[1];
		  } else {
		    cur_type.value = curcheck_id.value[0];
		  }
	  }
      

      if (res.data.length < 1) {
        cur_type.value = "-1";
      }

      state.params.type_id = cur_type;
    } else {
      failMsg(res.message);
    }
  });
};

onMounted(async () => {
  getLeftFun("sale");
});

const edit_model = ref(false);
const editForm = ref({
  aaa: "",
  bbb: ""
});
const tableEditorAuth = computed(() => {
  let flag = false;

  if (!!authArr.value?.mergeCard?.show) {
    flag = true;
  }
  return flag;
});

// 切换左侧商品类型
const change_prop_type = id => {
  console.log(id);
  getLeftFun(id);
  searchbarRef.value.clear();
};

const edit_modal_arr = ref({ curField: "", curval: "", rowKey: "" });

// 表格编辑事件
const handleEditorClick: MerakXTableInstance["onEditor-click"] = params => {
  console.log(params);
  edit_model.value = true;
  edit_modal_arr.value.curField = params.field;
  edit_modal_arr.value.rowKey = params.rowKey;
  edit_modal_arr.value.curval = params.value;
};
</script>

<style scoped lang="scss">
:deep(.merak_modal.xq .el-form .el-form-item__label) {
  justify-content: flex-end;
}

.merak-aside {
  display: flex;
  flex-direction: column;

  .tree-wrapper {
    flex: 1;
    min-height: 0;
  }
}

.el-tree {
  :deep(.el-tree-node.is-checked .el-tree-node__content:has(.is-leaf)) {
    color: #fff !important;
    background-color: var(--el-color-primary) !important;
  }
}

.translation {
  /* display: flex;
			flex-direction: column;
			width: 100%;*/
  height: 100%;
}

.translation_card {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;

  .table_main {
    /* display: flex;
				flex-direction: column;
				width: 100%;
				height: 100%; */
    flex: auto;
    min-height: 0;
  }
}

.translationPad {
  padding: 15px;
}

.dian {
  display: inline-block;
  width: 4px;
  height: 4px;
  border-radius: 50px;
  background-color: #fff;
  margin-right: 6px;
  position: relative;
  top: -2px;
}
.export {
  margin-bottom: var(--merak-space);
  text-align: right;
}
.xq .el-form-item__content {
  color: #303133;
  font-size: 13px;
}

:deep(.el-form-item__label) {
  padding-right: 40px;
}

:deep(.noCurCss.filter .el-scrollbar .el-tree--highlight-current .el-tree-node.is-current .el-tree-node__content) {
  background-color: #fff;
  color: var(--el-tree-text-color);
}

:deep(
    .noCurCss.filter
      .el-scrollbar
      .el-tree--highlight-current
      .el-tree-node.is-current
      > .el-tree-node__content
      .el-tree-node__label,
    .noCurCss.filter
      .el-scrollbar
      .el-tree--highlight-current
      .el-tree-node.is-current
      > .el-tree-node__content
      .el-tree-node__expand-icon
  ) {
  color: var(--el-tree-text-color);
}

:deep(.flx-justify-between.header) {
  display: none;
}

.merak-container-has-aside {
  position: relative;
}
</style>
